import React from "react";
// import { createHashHistory, createBrowserHistory } from "history";
import { createHashHistory, createBrowserHistory } from "./my-history";

import {
  Router,
  Routes,
  Route,
  useSearchParams,
  useNavigate,
  Outlet,
  useLocation,
  useParams,
} from "./my-react-router";
export {
  Routes,
  Route,
  useSearchParams,
  Outlet,
  useNavigate,
  useLocation,
  useParams,
};

export function HashRouter({ children }) {
  const historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createHashHistory();
  }

  const history = historyRef.current;
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  // 监听路径变化，就执行 setState
  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}

export function BrowserRouter({ children }) {
  const historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory();
  }
  const history = historyRef.current;
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  // 监听路径变化，就执行 setState
  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}

export function Link({ to, children, ...rest }) {
  const navigate = useNavigate();

  const handleClick = (ev) => {
    ev.preventDefault();
    navigate(to);
  };

  return (
    <a href={to} onClick={handleClick} {...rest}>
      {children}
    </a>
  );
}
